/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.meta.util;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import com.google.common.base.Charsets;
import com.google.common.collect.Lists;
import com.je.common.base.JsonBuilder;
import com.je.common.base.exception.PlatformException;
import com.je.common.base.exception.PlatformExceptionEnum;
import com.je.common.base.util.SystemProperty;
import com.je.common.base.util.ZipUtilExt;
import com.je.meta.model.PackageFile;
import com.je.meta.model.TransportPackageFile;
import java.io.*;
import java.util.Calendar;
import java.util.List;
import java.util.Map;

/**
 * 项目升级包工具类
 *
 * @author wangmm@ketr.com.cn
 * @date 2019/9/25
 */
public class UpgradeUtil {

    private static JsonBuilder jsonBuilder = JsonBuilder.getInstance();

    /**
     * 构建打包文件
     *
     * @param path 在zip中的路径
     * @param list 需要保存到文件中的集合数据
     * @return com.je.upgrade.model.PackageFile
     */
    public static PackageFile buildPackageFile(String path, List list) {
        return buildPackageFile(path, jsonBuilder.buildListPageJson(new Long(list.size()), list, false));
    }

    /**
     * 构建打包文件
     *
     * @param path 在zip中的路径
     * @param list 需要保存到文件中的集合数据
     * @return com.je.upgrade.model.PackageFile
     */
    public static TransportPackageFile buildStringContentPackageFile(String path, List list) {
        return buildStringContentPackageFile(path, jsonBuilder.buildListPageJson(new Long(list.size()), list, false));
    }

    /**
     * 构建打包文件
     *
     * @param path    在zip中的路径
     * @param content 文件内容
     * @return com.je.upgrade.model.PackageFile
     */
    public static PackageFile buildPackageFile(String path, String content) {
        //json转输入流
        ByteArrayInputStream in = IoUtil.toUtf8Stream(content);
        return new PackageFile(path, in);
    }

    /**
     * 构建打包文件
     *
     * @param path    在zip中的路径
     * @param content 文件内容
     * @return com.je.upgrade.model.PackageFile
     */
    public static TransportPackageFile buildStringContentPackageFile(String path, String content) {
        //json转输入流
        return new TransportPackageFile(path, content);
    }

    /**
     * 打包zip
     *
     * @param packageFiles 需要打包的文件集合
     * @return java.io.InputStream
     */
    public static ByteArrayInputStream buildZip(List<PackageFile> packageFiles) {
        List<String> paths = Lists.newArrayList();
        List<InputStream> ins = Lists.newArrayList();
        for (PackageFile p : packageFiles) {
            paths.add(p.getPath());
            ins.add(p.getIn());
        }
        try {
            //打包获取输入流
            return ZipUtilExt.zip(paths, ins, Charsets.UTF_8);
        } catch (Exception e) {
            e.printStackTrace();
            throw new PlatformException("zip生成失败!", PlatformExceptionEnum.JE_SYS_UPGRADE_PACKAGE_ERROR);
        }
    }

    /**
     * 获取文件内容
     *
     * @param fileMap 文件集合
     * @param path    想获取的路径
     * @return java.lang.String
     */
    public static String readContentString(Map<String, ByteArrayInputStream> fileMap, String path) {

        //验证文件是否存在
        if (!fileMap.containsKey(path)) {
            return null;
        }
        //获取文件流
        ByteArrayInputStream inputStream = fileMap.get(path);
        //inputStream转String
        return IoUtil.read(inputStream, Charsets.UTF_8);
    }

    /**
     * 缓存文件到本地
     *
     * @param is 文件流
     * @return java.io.FileInputStream
     */
    public static FileInputStream tempFile(InputStream is) {

        //临时文件存放目录
        File tempDir = FileUtil.mkdir(SystemProperty.getRootPath() + "/package_temp" + DateUtil.format(Calendar.getInstance().getTime(), "/yyyy/MMdd"));
        //创建临时文件
        File tempFile = FileUtil.createTempFile(tempDir, true);
        //写入文件内容
        FileUtil.writeFromStream(is, tempFile);
        try {
            //返回临时文件文件流
            return new FileInputStream(tempFile);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            throw new PlatformException("临时文件未找到", PlatformExceptionEnum.UNKOWN_ERROR, e);
        }
    }
}